package com.kaishengit.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.pms.entity.Employee;
import com.kaishengit.pms.util.DBHelp;
import com.kaishengit.pms.util.MapperRow;

public class EmployeeDao {

	private DBHelp<Employee> db = new DBHelp<Employee>();
	
	/**
	 * 通过用户名和密码查找用户
	 * @param username
	 * @param password
	 * @return
	 */
	public Employee getEmployeeByNameAndPwd(String username,String password) {
		String sql = "SELECT id,username,password,cookiepwd,enable FROM t_employee WHERE username=? AND password=?";
		return db.queryForObject(sql, new EmployeeMapper(), username,password);
	}
	
	private class EmployeeMapper implements MapperRow<Employee> {

		public Employee rowMapper(ResultSet rs) throws SQLException {
			Employee e = new Employee();
			e.setId(rs.getString("id"));
			e.setUsername(rs.getString("username"));
			e.setPassword(rs.getString("password"));
			e.setCookiepwd(rs.getString("cookiepwd"));
			e.setEnable(rs.getBoolean("enable"));
			return e;
		}
		
	}

	/**
	 * 通过cookie密码和用户名查找雇员
	 * @param username
	 * @param cookiepwd
	 * @return
	 */
	public Employee findByUsernameAndCpwd(String username, String cookiepwd) {
		String sql = "SELECT id,username,password,cookiepwd,enable FROM t_employee WHERE username=? AND cookiepwd=?";
		return db.queryForObject(sql, new EmployeeMapper(), username,cookiepwd);
	}

	//返回雇员列表
	public List<Employee> getAllEmployees() {
		String sql = "SELECT id,username,password,cookiepwd,enable FROM t_employee";
		return db.queryForList(sql, new EmployeeMapper());
	}
	
	//添加雇员信息
	public int saveEmployee(Employee em){
		String sql = "insert into t_employee (id,username,password,cookiepwd,enable) values(?,?,?,?,?)";
		return db.excuteSQL(sql, em.getId(),em.getUsername(),em.getPassword(),em.getCookiepwd(),em.isEnable());
		
	}

	//通过id查找雇员
	public Employee findById(String id) {
		String sql = "select id,username,password,cookiepwd,enable from t_employee where id = ?";
		return db.queryForObject(sql, new EmployeeMapper(), id);
	}

	//修改雇员信息
	public int updateEmployee(Employee em) {
		String sql = "update t_employee set username=?,password=?,cookiepwd=?,enable=? where id = ?";
		return db.excuteSQL(sql, em.getUsername(),em.getPassword(),em.getCookiepwd(),em.isEnable(),em.getId());
	}
	
	public List<Employee> getEnableEmployee(){
		String sql = "SELECT id,username,password,cookiepwd,enable FROM t_employee where enable = true";
		return db.queryForList(sql, new EmployeeMapper());
	}
}
